<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\func\Constant;
use app\common\func\Lib;
use app\common\func\Libs;
use app\common\func\Tools;
use app\common\model\PolicyAdjust;
use app\common\model\PolicyCash;
use app\common\model\PolicyProfit;
use app\common\model\PolicySimcard;
use app\common\model\PolicyStandard;
use app\common\model\PolicyStandards;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 政策设置
 *
 * @icon fa fa-circle-o
 */
class Policy extends Backend
{

    protected $searchFields = 'title';

    /**
     * Policy模型对象
     * @var \app\common\model\Policy
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Policy;
        $this->view->assign("mainTypeList", $this->model->getMainTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $query = $this->model;

            $query->where(["policy.status" => 1]);
            $list = $query->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','title','status','create_time']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        if($this->auth->isSuperAdmin()){
            $productList = \app\common\model\Product::where(["status" => 1])->select();
        }else{
            $productList = Lib::getUserProduct(1,$this->auth->getCompany()->id);
        }
        $list = [];
        foreach ($productList as $key => $val){
            $list[$val['id']] = $val['name'];
        }
        $this->view->assign("productList", $list);
        return $this->view->fetch();
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            if(!$this->auth->isSuperAdmin()){
                $company = $this->auth->getCompany();
                if(!$company){
                    $this->error(__('未绑定机构，请联系上级绑定！'));
                }
                $params['main_type'] = 1;
                $params['main_id'] = $company->id;
            }

            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function edit($ids = null)
    {
        $policy = $this->model->get($ids);

        if (false === $this->request->isPost()) {
            $productId = $policy->product_id;
            $product = Lib::getProductById($productId);
            if ($this->auth->isSuperAdmin()) {
                $cardList = Tools::getCardTypeObj("1,2");
                $tranList = \app\common\model\TransactionType::where(["status" => 1])->select();
                $rateList = \app\common\model\Rate::where(["status" => 1])->select();
                $channelList = \app\common\model\ConsumeChannel::where(["status" => 1])->select();
            } else {
                $cardList = Tools::getCardTypeObj($policy->card_type);
                $tranList = Lib::getTransactionTypeBYIds($policy->transaction_type_ids);
                $rateList = Lib::getRateListByIds($policy->rate_ids);
                $channelList = Lib::getChannelByIds($policy->channel_ids);
            }

            $profit = Libs::getPolicyProfitList($policy->id);
            $flow = Libs::getPolicyFlow($policy->id);
            $adjust = Libs::getPolicyAdjust($policy->id);
            $standard = Libs::getPolicyStandard($policy->id);
            $standards = Libs::getPolicyStandards($policy->id);
            if(count($standards)){
                foreach ($standards as $key => $val){
                    $val->name = Constant::$levelInfo[$val->role]['name'];
                }
            }

            $this->view->assign("profit", $profit);
            $this->view->assign("flow", $flow);
            $this->view->assign("adjust", $adjust);
            $this->view->assign("standard", $standard);
            $this->view->assign("standards", $standards);
            $this->assignconfig("policy_id", $policy->id);
            $this->view->assign("policy_id", $policy->id);

            $this->view->assign('product', $product);
            $this->view->assign('row', $policy);
            $this->view->assign("card_list", $cardList);
            $this->view->assign("tran_list", $tranList);
            $this->view->assign("rate_list", $rateList);
            $this->view->assign("channel_list", $channelList);
            $this->view->assign("is_admin", $this->auth->isSuperAdmin());
            $this->view->assign("product_id", $productId);
            $this->assignconfig("product_id", $productId);
            $this->assignconfig("is_admin", $this->auth->isSuperAdmin());
            return $this->view->fetch();
        }

        $params = $this->request->post();

        $result = false;
        $msg = __('No rows were updated');
        Db::startTrans();
        try {
            $policy->title = $params['title'];
            $policy->product_id = $params['product_id'];
            $policy->card_type = implode(",",$params['card_type']);
            $policy->transaction_type_ids = implode(",",$params['transaction_type_ids']);
            $policy->rate_ids = implode(",",$params['rate_ids']);
            $policy->status = $params['status'];
            $policy->save();

            $profit = Libs::getPolicyProfitList($policy->id);
            if(count($params['profit_rate']) > 0){
                if(count($profit) > 0){
                    foreach ($profit as $item){
                        $item->delete();
                    }
                }
                $profitData = [];
                for ($i = 0;$i < count($params['profit_rate']);$i++){
                    $profitData[] = [
                        "policy_id" => $policy->id,
                        "product_id" => $params['product_id'],
                        "profit_rate" => $params['profit_rate'][$i],
                        "profit_profit" => $params['profit'][$i],
                    ];
                }
                $profit = new PolicyProfit();
                $profit->saveAll($profitData);
            }

            if(isset($params['flow_agent']) && $params['flow_agent'] > 0){
                $flow = Libs::getPolicyFlow($policy->id);
                if(!$flow ){
                    $flow = new PolicySimcard();
                    $flow->policy_id = $policy->id;
                    $flow->product_id = $params['product_id'];
                }
                $flow->agent = $params['flow_agent'];
                $flow->agency = isset($params['flow_agency']) && $params['flow_agency'] > 0 ? $params['flow_agency'] : 0;
                $flow->core = isset($params['flow_core']) && $params['flow_core'] > 0 ? $params['flow_core'] : 0;
                $flow->save();
            }

            if(isset($params['adjust_agent']) && $params['adjust_agent'] > 0){
                $adjust = Libs::getPolicyAdjust($policy->id);
                if(!$adjust){
                    $adjust = new PolicyAdjust();
                    $adjust->policy_id = $policy->id;
                    $adjust->product_id = $params['product_id'];
                }
                $adjust->agent = $params['adjust_agent'];
                $adjust->agency = isset($params['adjust_agency']) && $params['adjust_agency'] > 0 ? $params['adjust_agency'] : 0;
                $adjust->core = isset($params['adjust_core']) && $params['adjust_core'] > 0 ? $params['adjust_core'] : 0;
                $adjust->save();
            }

            //新达标
            $standards = Libs::getPolicyStandards($policy->id);
            if(isset($params['standard_reward']) && count($params['standard_reward']) > 0){
                if(count($standards) > 0){
                    foreach ($standards as $item){
                        $item->delete();
                    }
                }
                $standardData = [];
                for ($i = 0;$i < count($params['standard_reward']);$i++){
                    $standardData[] = [
                        "policy_id" => $policy->id,
                        "product_id" => $params['product_id'],
                        "role" => $params['standard_role'][$i],
                        "day_limit" => $params['standard_day'][$i],
                        "money" => $params['standard_money'][$i],
                        "reward" => $params['standard_reward'][$i],
                    ];
                }
                $standards = new PolicyStandards();
                $standards->saveAll($standardData);
            }

            //旧达标
            $standard = Libs::getPolicyStandard($policy->id);
            if(isset($params['day_limit']) && count($params['day_limit']) > 0){
                if(count($standard) > 0){
                    foreach ($standard as $item){
                        $item->delete();
                    }
                }
                $standardData = [];
                for ($i = 0;$i < count($params['day_limit']);$i++){
                    $standardData[] = [
                        "policy_id" => $policy->id,
                        "product_id" => $params['product_id'],
                        "day_start" => $params['day_start'][$i],
                        "day_limit" => $params['day_limit'][$i],
                        "money" => $params['money'][$i],
                        "agent" => isset($params['standard_agent']) ? $params['standard_agent'][$i] : 0,
                        "agency" => isset($params['standard_agency']) ? $params['standard_agency'][$i] : 0,
                        "core" => isset($params['standard_core']) ? $params['standard_core'][$i] : 0,
                    ];
                }
                $standard = new PolicyStandard();
                $standard->saveAll($standardData);
            }
            $result = true;

            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        if (false === $result) {
            $this->error($msg);
        }
        $this->success();
    }

    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count = Lib::getEquipByPolicy($item->id);
                if($count > 0){
                    $this->error("已绑定设备，不可删除！");
                }
                $item->status = 2;
                if($item->save()){
                    $count += 1;
                }
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    public function product(){
        if (false === $this->request->isPost()) {
            if($this->auth->isSuperAdmin()){
                $productList = \app\common\model\Product::where(["status" => 1])->select();
            }else{
                $productList = Lib::getUserProduct(1,$this->auth->getCompany()->id);
            }
            $this->view->assign("product_list",$productList);
            $this->view->assign("is_admin",$this->auth->isSuperAdmin());
            $this->assignconfig("is_admin",$this->auth->isSuperAdmin());
            return $this->view->fetch();
        }
    }

    public function verify(){
        $productId = $this->request->post('product_id');

        $list = lib::getProductPolicy(1, $this->auth->getCompany()->id, $productId);
        $count = count($list);

        $this->success("","",["count" => $count,"policy_id" => $count == 1 ? $list[0]['id'] : 0]);
    }

    public function list(){
        if (false === $this->request->isPost()) {
            $productId = $this->request->get('product_id');

            $list = lib::getProductPolicy(1, $this->auth->id, $productId);

            $this->view->assign("policy_list",$list);
            $this->assignconfig("product_id",$productId);
            return $this->view->fetch();
        }
    }

    public function profit(){
        $policyId = $this->request->post('policy_id');
        $cardId = $this->request->post('card_id');
        $tranId = $this->request->post('tran_id');
        $rateId = $this->request->post('rate_id');
        $channelId = $this->request->post('channel_id');

        $profit = Lib::getPolicyProfit($policyId,$cardId,$tranId,$rateId,$channelId);

        $this->success("","",["base" => $profit->profit_base,"hide" => $profit->profit_hide]);
    }

    public function setting($ids){
        $productId = $ids;
        if (false === $this->request->isPost()) {
            if($this->auth->isSuperAdmin()){
                $cardList = Tools::getCardTypeObj("1,2");
                $tranList = \app\common\model\TransactionType::where(["status" => 1])->select();
                $rateList = \app\common\model\Rate::where(["status" => 1])->select();
                $profitList = Constant::$profitList;
            }else{
                $policyId = $this->request->get('policy_id');
                $policy = Lib::getPolicy($policyId);
                $cardList = Tools::getCardTypeObj($policy->card_type);
                $tranList = Lib::getTransactionTypeBYIds($policy->transaction_type_ids);
                $rateList = Lib::getRateListByIds($policy->rate_ids);

                $cash = Lib::getPolicyCash($policy->id);
                $flow = Lib::getPolicyFlow($policy->id);
                $standard = Lib::getPolicyStandard($policy->id);

                $this->view->assign("cash",$cash);
                $this->view->assign("flow",$flow);
                $this->view->assign("standard",$standard);
                $this->assignconfig("policy_id",$policy->id);
                $this->view->assign("policy_id",$policy->id);
            }

            $this->view->assign("card_list",$cardList);
            $this->view->assign("tran_list",$tranList);
            $this->view->assign("rate_list",$rateList);
            $this->view->assign("profit_list",$profitList);
            $this->view->assign("is_admin",$this->auth->isSuperAdmin());
            $this->view->assign("product_id",$productId);
            $this->assignconfig("product_id",$productId);
            $this->assignconfig("is_admin",$this->auth->isSuperAdmin());
            return $this->view->fetch();
        }

        $params = $this->request->post();

        $defaultPolicy = Libs::getPolicyByProduct($params['product_id']);
        if($defaultPolicy){
            $this->error("该产品政策已存在！");
        }

        $result = false;
        $msg = __('No rows were updated');
        Db::startTrans();
        try {
            $policy = new \app\common\model\Policy();

            $policy->title = $params['title'];
            $policy->product_id = $params['product_id'];
            $policy->card_type = implode(",",$params['card_type']);
            $policy->transaction_type_ids = implode(",",$params['transaction_type_ids']);
            $policy->rate_ids = implode(",",$params['rate_ids']);
            $policy->status = $params['status'];
            $res = $policy->save();
            if($res){
                if(isset($params['profit_rate']) && count($params['profit_rate']) > 0){
                    $profitData = [];
                    for ($i = 0;$i < count($params['profit_rate']);$i++){
                        $profitData[] = [
                            "policy_id" => $policy->id,
                            "product_id" => $params['product_id'],
                            "profit_rate" => $params['profit_rate'][$i],
                            "profit_profit" => $params['profit'][$i],
                        ];
                    }
                    $profit = new PolicyProfit();
                    $profit->saveAll($profitData);
                }

                if(isset($params['flow_agent']) && $params['flow_agent'] > 0){
                    $flow = new PolicySimcard();
                    $flow->policy_id = $policy->id;
                    $flow->product_id = $params['product_id'];
                    $flow->agent = $params['flow_agent'];
                    $flow->agency = isset($params['flow_agency']) && $params['flow_agency'] > 0 ? $params['flow_agency'] : 0;
                    $flow->core = isset($params['flow_core']) && $params['flow_core'] > 0 ? $params['flow_core'] : 0;
                    $flow->save();
                }

                if(isset($params['adjust_agent']) && $params['adjust_agent'] > 0){
                    $adjust = new PolicyAdjust();
                    $adjust->policy_id = $policy->id;
                    $adjust->product_id = $params['product_id'];
                    $adjust->agent = $params['adjust_agent'];
                    $adjust->agency = isset($params['adjust_agency']) && $params['adjust_agency'] > 0 ? $params['adjust_agency'] : 0;
                    $adjust->core = isset($params['adjust_core']) && $params['adjust_core'] > 0 ? $params['adjust_core'] : 0;
                    $adjust->save();
                }

                //新达标
                if(isset($params['standard_reward']) && count($params['standard_reward']) > 0){
                    $standardData = [];
                    for ($i = 0;$i < count($params['standard_reward']);$i++){
                        $standardData[] = [
                            "policy_id" => $policy->id,
                            "product_id" => $params['product_id'],
                            "role" => $params['standard_role'][$i],
                            "day_limit" => $params['standard_day'][$i],
                            "money" => $params['standard_money'][$i],
                            "reward" => $params['standard_reward'][$i],
                        ];
                    }
                    $standards = new PolicyStandards();
                    $standards->saveAll($standardData);
                }

                //旧达标
                if(isset($params['day_limit']) && count($params['day_limit']) > 0){
                    $standardData = [];
                    for ($i = 0;$i < count($params['day_limit']);$i++){
                        $standardData[] = [
                            "policy_id" => $policy->id,
                            "product_id" => $params['product_id'],
                            "day_start" => $params['day_start'][$i],
                            "day_limit" => $params['day_limit'][$i],
                            "money" => $params['money'][$i],
                            "agent" => isset($params['standard_agent']) ? $params['standard_agent'][$i] : 0,
                            "agency" => isset($params['standard_agency']) ? $params['standard_agency'][$i] : 0,
                            "core" => isset($params['standard_core']) ? $params['standard_core'][$i] : 0,
                        ];
                    }
                    $standard = new PolicyStandard();
                    $standard->saveAll($standardData);
                }
                $result = true;

            }else{
                $msg = "信息保存失败，请刷新后重试！";
            }
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }

        if (false === $result) {
            $this->error($msg);
        }
        $this->success();
    }

}
